<?php
/**
 * Functions    系统函数
 * @copyright   Copyright(c) 2015
 * @author      tianjie
 * @version     2.0
 **/

use tian\App;
use tian\Request;
use tian\Response;
use tian\Url;
use tian\Log;
use tian\Clear;
use tian\Redis;

if (!function_exists('input')) {
    /**
     * 获取输入数据 支持默认值和过滤
     * @param string $key 获取的变量名
     * @param mixed $default 默认值
     * @param string $filter 过滤方法
     * @return mixed
     */
    function input(string $key = '', $default = null, $filter = '')
    {
        if (0 === strpos($key, '?')) {
            $key = substr($key, 1);
            $has = true;
        }
        if ($pos = strpos($key, '.')) {
            // 指定参数来源
            list($method, $key) = explode('.', $key, 2);
            if (!in_array($method, ['get', 'post', 'put', 'param', 'file'])) {
                $key = $method . '.' . $key;
                $method = 'param';
            }
        } else {
            // 默认为自动判断
            $method = 'param';
        }
        if (isset($has)) {
            return request()->has($key, $method, $default);
        } else {
            return request()->$method($key, $default, $filter);
        }
    }
}

if (!function_exists('request')) {
    /**
     * 获取当前Request对象实例
     * @return Request
     */
    function request()
    {
        return Request::instance();
    }
}

if (!function_exists('redis')) {
    /**
     * 获取当前Request对象实例
     * @return Request
     */
    function redis()
    {
        $config = config("redis")['default'];
        return Redis::getInstance($config);
    }
}

if (!function_exists('url')) {
    /**
     * Url生成
     * @param string $url 路由地址
     * @param string|array $vars 变量
     * @return string
     */
    function url(string $str = '', array $ary = []): string
    {
        return Url::create($str, $ary);
    }
}

if (!function_exists('json')) {
    /**
     * @param mixed $data 返回的数据
     * @return string
     */
    function json($data = []): string
    {
        header('Content-Type: text/html; charset=utf-8');
        header("Access-Control-Allow-Origin:*"); // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Headers:DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Typ');
        header('Access-Control-Allow-Methods:PUT,POST,GET,DELETE,OPTIONS');

        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }
}

if (!function_exists('setLog')) {
    /**
     * 日志记录
     * @param string $content 日志内容
     * @param string $type 日志类型
     * @return void
     */
    function setLog(string $content, string $type = 'log')
    {
        Log::write($content, $type);
    }
}

if (!function_exists('clear')) {
    /**
     * 助手函数 清除缓存
     * @param string $type 类型 cache|log|views
     * @return void
     */
    function clear(string $type = 'all')
    {
        Clear::del($type);
    }
}

if (!function_exists('model')) {
    /**
     * 助手函数 实例化Model
     * @param string $name Model名称
     * @return object
     * @throws Exception 异常
     */
    function model(string $name = ''): object
    {
        $class = '\\app\\model\\' . $name;

        if (class_exists($class)) {
            $model = new $class();
        } else {
            $module = request()->module();
            $class = "\\app\\" . $module . "\\model\\" . $name;
            if (class_exists($class)) {
                $model = new $class();
            } else {
                throw new Exception('class not exists:' . $class);
            }
        }

        if (config('page')['think_paginator'] != '') {
            \think\Paginator::maker(function ($items, $listRows, $currentPage, $total, $simple, $options) {
                $class = config('page')['think_paginator'];
                return new $class($items, $listRows, $currentPage, $total, $simple, $options);
            });
        }

        return $model;
    }
}

if (!function_exists('config')) {
    /**
     * 读取配置文件内容
     * @param string $name
     * @return null
     */
    function config(string $name)
    {
        if ($name) {
            return App::getConfig($name);
        }
        return null;
    }
}

if (!function_exists('redirect')) {
    /**
     * 重定向
     * @param string|null $url
     * @return void
     */
    function redirect(string $url = null)
    {
        if ($url == null) {
            $url = '/';
        }
        header('content-type:text/html;charset=uft-8');
        header("Location: $url");
        exit();
    }
}

/**
 * 驼峰命名转下划线命名，如 UserName => user_name
 * @param string $s
 * @return string
 */
function toUnderLineName(string $s): string
{
    $s = lcfirst($s);
    $chars = str_split($s);
    $res = "";
    foreach ($chars as $c) {
        if (isCapitalLetter($c)) {
            $c = "_" . strtolower($c);
        }
        $res .= $c;
    }
    return $res;
}

/**
 * 判断字符串是否为大写字母
 * @param string $c
 * @return boolean
 */
function isCapitalLetter(string $c): bool
{
    if (preg_match('/^[A-Z]+$/', $c)) {
        return true;
    } else {
        return false;
    }
}

//获取目录下所有文件，包括子目录
function get_filenamesbydir($dir)
{
    $files = [];
    get_allfiles($dir, $files);
    return $files;
}

function get_allfiles($path, &$files)
{
    if (is_dir($path)) {
        $dp = dir($path);
        while ($file = $dp->read()) {
            if ($file !== "." && $file !== "..") {
                get_allfiles($path . "/" . $file, $files);
            }
        }
        $dp->close();
    }
    if (is_file($path)) {
        $files[] = [
            'path' => $path,
            'name' => trim(strrchr($path, '/'), '/')
        ];
    }
}